using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace SmartLink.Infrastructure
{
    public class NopiExcelHelper
    {
        /// <summary>
        /// DataTable导出到Excel文件
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">保存位置</param>
        /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
        public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
        {
            using (MemoryStream ms = Export(dtSource, strHeaderText))
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
            }
        }

        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
            XSSFWorkbook workbook = new XSSFWorkbook();
            ISheet sheet; //= workbook.CreateSheet();

            if (!String.IsNullOrEmpty(dtSource.TableName))
            {
                sheet = workbook.CreateSheet(dtSource.TableName);
            }
            else
            {
                sheet = workbook.CreateSheet();
            }

            #region 右击文件 属性信息
            {
                //DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                //dsi.Company = "http://www.yongfa365.com/";
                //workbook.DocumentSummaryInformation = dsi;

                //SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                //si.Author = "柳永法"; //填加xls文件作者信息
                //si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
                //si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
                //si.Comments = "说明信息"; //填加xls文件作者信息
                //si.Title = "NPOI测试"; //填加xls文件标题信息
                //si.Subject = "NPOI测试Demo";//填加文件主题信息
                //si.CreateDateTime = DateTime.Now;
                //workbook.SummaryInformation = si;
            }
            #endregion

            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    if (dtSource.Rows[i][j].ToString().Length > 100)
                    {
                        break;
                    }
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }



            int rowIndex = 0;

            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表，填充表头，填充列头，样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        if (!String.IsNullOrEmpty(dtSource.TableName))
                        {
                            sheet = workbook.CreateSheet(dtSource.TableName);
                        }
                        else
                        {
                            sheet = workbook.CreateSheet();
                        }

                    }

                    #region 表头及样式
                    {
                        IRow headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        headerRow.GetCell(0).CellStyle = headStyle;

                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        //headerRow.Dispose();
                    }
                    #endregion


                    #region 列头及样式
                    {
                        IRow headerRow = sheet.CreateRow(1);


                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);


                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);

                        }
                        //headerRow.Dispose();
                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion


                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }


            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                //sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet
                return ms;
            }

        }

        /// <summary>
        /// 根据模板生成excel文件
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="strHeaderText"></param>
        /// <returns></returns>
        public static MemoryStream ExportByModel(DataTable dtSource, string strFileName)
        {
            XSSFWorkbook IWorkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook = new XSSFWorkbook(file);
            }

            ICellStyle dateStyle = IWorkbook.CreateCellStyle();
            IDataFormat format = IWorkbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            ISheet sheet = IWorkbook.GetSheetAt(0);
            int rowIndex = sheet.LastRowNum + 1;

            foreach (DataRow row in dtSource.Rows)
            {
                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion
                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                IWorkbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                //释放sheet ??

                return ms;
            }
        }

        /// <summary>
        /// 用于Web导出
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">文件名</param>
        /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
        public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
        {
            byte[] buffer = Export(dtSource, strHeaderText).GetBuffer();
            _ExportbyWeb(strFileName, buffer);
        }

        public static void ExportByWebByModel(DataTable dtSource, string modelfilename, string strFileName)
        {
            byte[] buffer = ExportByModel(dtSource, modelfilename).GetBuffer();
            _ExportbyWeb(strFileName, buffer);
        }

        private static void _ExportbyWeb(string strFileName, byte[] buffer)
        {
            HttpContext curContext = HttpContext.Current;

            // 设置编码和附件格式
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(strFileName), Encoding.UTF8));
            curContext.Response.BinaryWrite(buffer);
            curContext.Response.End();
        }


        ///// <summary>读取excel
        ///// 默认第一行为标头
        ///// </summary>
        ///// <param name="strFileName">excel文档路径</param>
        ///// <returns></returns>
        //public static DataTable Import(string strFileName)
        //{
        //    DataTable dt = new DataTable();

        //    IWorkbook IWorkbook;
        //    using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
        //    {
        //        IWorkbook = new IWorkbook(file);
        //    }
        //    HSSFSheet sheet = IWorkbook.GetSheetAt(0);
        //    System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

        //    IRow headerRow = sheet.GetRow(0);
        //    int cellCount = headerRow.LastCellNum;

        //    for (int j = 0; j < cellCount; j++)
        //    {
        //        ICell cell = headerRow.GetCell(j);
        //        dt.Columns.Add(cell.ToString());
        //    }

        //    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
        //    {
        //        IRow row = sheet.GetRow(i);
        //        DataRow dataRow = dt.NewRow();

        //        for (int j = row.FirstCellNum; j < cellCount; j++)
        //        {
        //            if (row.GetCell(j) != null)
        //                dataRow[j] = row.GetCell(j).ToString();
        //        }

        //        dt.Rows.Add(dataRow);
        //    }
        //    return dt;
        //}

        /// <summary>
        /// 读取excel
        /// </summary>
        /// <param name="strFileName">excel文档路径</param>
        /// <param name="ishead">是否有标头</param>
        /// <returns></returns>
        public static DataTable Import(string strFileName, Boolean ishead)
        {
            DataTable dt = new DataTable();

            XSSFWorkbook IWorkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                //IWorkbook = new XSSFWorkbook(file);
                IWorkbook = new XSSFWorkbook(file);
            }
            ISheet sheet = IWorkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }
            int startind = 0;
            if (ishead)
            {
                startind = startind + 1;
            }

            for (int i = startind; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = getnewrow(dt, cellCount, row);

                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        private static DataRow getnewrow(DataTable dt, int cellCount, IRow row)
        {
            DataRow dataRow = dt.NewRow();

            for (int j = row.FirstCellNum; j < cellCount; j++)
            {
                //if (row.GetCell(j) != null)
                //    dataRow[j] = row.GetCell(j).ToString();
                ICell cell = row.GetCell(j);
                if (cell == null)
                {
                    dataRow[j] = null;
                }
                else
                {
                    switch (cell.CellType)
                    {
                        case CellType.Blank:
                            dataRow[j] = null;
                            break;
                        case CellType.Boolean:
                            dataRow[j] = cell.BooleanCellValue;
                            break;
                        case CellType.Numeric:
                            if (HSSFDateUtil.IsCellDateFormatted(cell))
                            {
                                dataRow[j] = cell.DateCellValue;
                            }
                            else
                            {
                                dataRow[j] = cell.NumericCellValue;
                            }
                            break;
                        case CellType.String:
                            dataRow[j] = cell.StringCellValue;
                            break;
                        case CellType.Error:
                            dataRow[j] = cell.ErrorCellValue;
                            break;
                        case CellType.Formula:
                        default:
                            dataRow[j] = "=" + cell.CellFormula;
                            break;
                    }
                }
            }

            return dataRow;
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="strFileName">Excel文件全路径(服务器路径)</param>  
        /// <param name="SheetName">要获取数据的工作表名称</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(string strFileName, string SheetName, int HeaderRowIndex)
        {
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook workbook = new XSSFWorkbook(file);
                return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
            }
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="strFileName">Excel文件全路径(服务器路径)</param>  
        /// <param name="SheetIndex">要获取数据的工作表序号(从0开始)</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(string strFileName, int SheetIndex, int HeaderRowIndex)
        {
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook workbook = new XSSFWorkbook(file);
                string SheetName = workbook.GetSheetName(SheetIndex);
                return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
            }
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="ExcelFileStream">Excel文件流</param>  
        /// <param name="SheetName">要获取数据的工作表名称</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
        {
            XSSFWorkbook workbook = new XSSFWorkbook(ExcelFileStream);
            ExcelFileStream.Close();
            return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="ExcelFileStream">Excel文件流</param>  
        /// <param name="SheetIndex">要获取数据的工作表序号(从0开始)</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex)
        {

            XSSFWorkbook workbook = new XSSFWorkbook(ExcelFileStream);
            ExcelFileStream.Close();
            string SheetName = workbook.GetSheetName(SheetIndex);
            return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);

        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="workbook">要处理的工作薄</param>  
        /// <param name="SheetName">要获取数据的工作表名称</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string SheetName, int HeaderRowIndex)
        {
            ISheet sheet = workbook.GetSheet(SheetName);
            DataTable table = new DataTable();
            try
            {
                IRow headerRow = sheet.GetRow(HeaderRowIndex);
                int cellCount = headerRow.LastCellNum;

                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }

                int rowCount = sheet.LastRowNum;

                #region 循环各行各列,写入数据到DataTable
                for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = getnewrow(table, cellCount, row);
                    table.Rows.Add(dataRow);
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                table.Clear();
                table.Columns.Clear();
                table.Columns.Add("出错了");
                DataRow dr = table.NewRow();
                dr[0] = ex.Message;
                table.Rows.Add(dr);
                return table;
            }
            finally
            {
                //sheet.Dispose();  
                workbook = null;
                sheet = null;
            }
            #region 清除最后的空行
            for (int i = table.Rows.Count - 1; i > 0; i--)
            {
                bool isnull = true;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (table.Rows[i][j] != null)
                    {
                        if (table.Rows[i][j].ToString() != "")
                        {
                            isnull = false;
                            break;
                        }
                    }
                }
                if (isnull)
                {
                    table.Rows[i].Delete();
                }
            }
            #endregion
            return table;
        }

    }
}
